"""Utility module for xross-share"""

from django.utils import simplejson as json

import os

_application_url = os.environ['HTTP_HOST']

def render_json_response(response_obj, json_context=None):
	"""Renders an AppEngine webapp Response object with a JSON
response message.
response_obj is a webapp.Response object
json_context is a JSON serializable object
Throws TypeError on invalid Response object.
	"""
	from google.appengine.ext.webapp import Response

	# Will throw a TypeError if json_context is not JSON serializable
	response_obj.headers['Content-type'] = 'application/json'
	# Pretty print to Response output
	json.dump(json_context, response_obj.out, sort_keys=True, indent=4)
	
def get_img_url(data_key):
	"""Formats a URL to serve an image using the data key"""
	full_url = '%s/fetch/image?img_key=%s' % (_application_url, data_key)
	return full_url
	
def notify_android(device_key):
	"""Uses C2DM to notify the android device that new data exists for it."""
	pass
	# TODO Implement
	
def notify_bb(device_key):
	"""Notifies the BlackBerry device that new data exists for it."""
	pass
	# TODO Implement
	
def notify_chrome_ext(device_key):
	"""Uses the Channel API to notify the Google Chrome extension client of a 
new message. This will only succeed if the client is listening on an open
channel."""
	from google.appengine.api import channel
	message = { 'data_available': True }
	channel.send_message(device_key, json.dumps(message))
